﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.Web.UI.Controls;
using ZX.SYS.Bussiness;
using System.Data;
using ZX.BLL.Extend;
using ZX.EHR.Library;
using ZX.DBModule;
using ZX.BLL;
using System.Web.Security;
using ZX.SYS.Library;
using System.Text.RegularExpressions;
using System.Configuration;
namespace ZX.WebApp.Message
{
    public partial class msgbody : BasePage
    {
        public static readonly string SmsTongji = ConfigurationManager.AppSettings["SmsTongji"].ToString();
        public static readonly string SmsUsern = ConfigurationManager.AppSettings["SmsUname"].ToString();
        public static readonly string SmsUpass = ConfigurationManager.AppSettings["SmsUpass"].ToString();
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        public string getdata(string Url)
        {
            MQOut mo = new MQOut();
            return mo.GetPageContent(Url, string.Empty);
        }
        protected void btnsendOnClick(object sender, EventArgs e)
        {
            string beforeSend= getdata(SmsTongji + "?username=" + SmsUsern + "&password=" + SmsUpass);

            double wenzinums =0;
            int sendednums = 1;//短信字数、发送电话号码数
            string userid = PM.Value;
            string[] userids, userps, userns;
            string userp, usern;
            string users = txtPM.Value;
            string messa = txtMODEL.Value;
            if (messa.Length > 300)
            {
                Labmes.Text = "字数限制：短信字数超过300，请裁剪后发送！";
                return;
            }
            else
            {
               wenzinums= Math.Ceiling(messa.Length/70.00);
            }
            string op = selectOption.SelectedValue;
            MQproccess mqp = new MQproccess();
            string back = "";
            DateTime dtime=DateTime.Now;
            if (PlanTime.Value != "")
                dtime = Convert.ToDateTime(PlanTime.Value);
            if (op == "2" && userid!="")
            {
                DataTable dt = mqp.GetUserType(userid);
                DataRow[] dr = dt.Select();
                sendednums = dr.Length;
                if (dr.Length > 0)
                {
                    for (int i = 0; i < dr.Length; i++)
                    {
                        string view="<" + dr[i]["Xing"].ToString() + dr[i]["Ming"].ToString() + ">" + dr[i]["ShouJi"].ToString();
                        if (dtime > DateTime.Now)//定时发送
                        {
                            mqp.insert(ReMeg(messa, dr[i], ""), dtime, dr[i]["ShouJi"].ToString(), 0, User.UserID);
                            back +=view +": 定时成功,届时发送！<br/>";
                        }
                        else
                        {
                            string ret= mqp.sendmessage(dr[i]["ShouJi"].ToString(), ReMeg(messa, dr[i], ""));
                            if (ret == "0")//发送成功
                            {
                                mqp.insert(ReMeg(messa, dr[i], ""), dtime, dr[i]["ShouJi"].ToString(), 1, User.UserID);
                                back += view + ": 发送成功！<br/>";
                            }
                            else
                            {
                                back += view + ":发送失败！原因："+ret+"；<br/>";
                                //mqp.insert(ReMeg(messa, dr[i], ""), dtime, dr[i]["ShouJi"].ToString(), 0, User.UserID);
                            }
                        }
                    
                    }
                }
                else
                    back += "该组无成员，无法发送!";
                users = "";//后面不再执行
            }

            if (users != "" && users != string.Empty)
            {
                userp = Regex.Replace(users, "<[^> ]*>", "");
                usern = Regex.Replace(users.Replace("<", "") + ",", ">[^, ]*,", ",").TrimEnd(',');
                
                if (userid.Contains(","))
                {
                    userids = userid.Split(',');
                    userps = userp.Split(',');
                    userns = usern.Split(',');
                    sendednums = userps.Length;
                    for (int i = 0; i < userids.Length; i++)
                    {
                        string view = "<" + userns[i] + ">" + userps[i];
                        if (dtime > DateTime.Now)//当时间大于现在,定时发送
                        {
                        
                            mqp.insert(ReMeg(messa, null, userns[i].Substring(0,1)), dtime, userps[i], 0, User.UserID);
                            back +=view + ": 定时成功,届时发送！<br/>";
                       
                        }
                        else
                        {
                            string ret=mqp.sendmessage(userps[i], ReMeg(messa, null, userns[i].Substring(0,1)));
                            if (ret == "0")//发送成功
                            {
                                mqp.insert(ReMeg(messa, null, userns[i].Substring(0, 1)), dtime, userps[i], 1, User.UserID);
                                back += view + ": 发送成功！<br/>";
                            }
                            else
                            {
                                back += view + ": 发送失败！原因：" + ret + "；<br/>";
                                //mqp.insert(ReMeg(messa, null, userns[i].Substring(0, 1)), dtime, userps[i], 0, User.UserID);
                            }
                        }
                    }
                }
                else
                {
                    string view = "<" + usern + ">" + userp;
                    if (dtime > DateTime.Now)//当时间大于现在,定时发送
                    {
                        mqp.insert(ReMeg(messa, null,usern.Substring(0, 1)), dtime, userp, 0, User.UserID);
                        back += view + ": 定时成功,届时发送！<br/>";
                    }
                    else
                    {
                        string ret = mqp.sendmessage(userp, ReMeg(messa, null, usern.Substring(0, 1)));
                        if ( ret== "0")//发送成功
                        {
                            mqp.insert(ReMeg(messa, null, usern.Substring(0, 1)), dtime, userp, 1, User.UserID);
                            back += view + ": 发送成功！<br/>";
                        }
                        else
                        {
                            back += view + ": 发送失败！原因：" + ret + "；<br/>";
                            //mqp.insert(ReMeg(messa, null, usern.Substring(0, 1)), dtime, userp, 0, User.UserID);
                        }
                    }
                }
            }
            //string afterSend = getdata(SmsTongji + "?username=" + SmsUsern + "&password=" + SmsUpass);
            string SendNums = "发送前短信剩余：" + beforeSend + " 条，本次估计发送：" + wenzinums * sendednums + "条，但具体请以供应商提供的为准，现在剩余短信量请查看统计页面<br/>具体发送明细如下：<br/>";
            //try
            //{
            //    SendNums += (Convert.ToInt32(beforeSend) - Convert.ToInt32(afterSend)).ToString()+"条；<br>";
            //}
            //catch (Exception ex)
            //{
            //    SendNums = "无法获取短信剩余量，此次发送条数暂无法计算。<br>";
            //}

            Labmes.Text =SendNums+ back;
            //ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>RefreshData();</script>");
           
        }

        /// <summary>
        /// 短信模板替换
        /// </summary>
        /// <param name="meg">原始短信</param>
        /// <param name="dr">匹配行</param>
        /// <param name="Xing">无匹配行时只匹配姓</param>
        /// <returns>返回转换后的短信内容</returns>
        public string ReMeg(string meg, DataRow dr, string Xing)
        { 
            string back="";
            if (Xing != "")
            {
                back = meg.Replace("{姓}",Xing);
            }
            else
            {
                back = meg.Replace("{姓}", dr["Xing"].ToString()).Replace("{名}", dr["Ming"].ToString()).Replace("{昵称}", dr["Nicheng"].ToString()).Replace("{手机号}", dr["ShouJi"].ToString()).Replace("{职位}", dr["ZhiYe"].ToString()).Replace("{生日}", dr["ShengRi"].ToString()).Replace("{公司}", dr["GongSi"].ToString());
            }
            return back;
        }

    }
}